<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <tree-table
        class="treeTable"
        :data="cateList"
        :columns="columns"
        :expand-type="false"
        :selection-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- //是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_delete === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCateName(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger "
            icon="el-icon-delete"
            size="mini"
            @click="removeUserById(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 添加分类弹框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="AddCateDialogVisible"
        width="50%"
        @close="addCateDialogClosed"
      >
        <!-- 内容主体区 -->
        <el-form
          :model="addCateForm"
          :rules="addCateFormRules"
          ref="addCateFormRef"
          label-width="100px"
        >
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类：">
            <el-cascader
              v-model="selectedKeys"
              :options="parentCateList"
              :props="cascaderProps"
              @change="parentCateChange"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="AddCateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改分类 -->
      <el-dialog
        title="修改分类"
        :visible.sync="editCateDialogVisible"
        width="50%"
        @close="editCateDialogClosed"
      >
        <!-- 内容主体区 -->
        <el-form
          :model="editCateForm"
          :rules="editCateFormRules"
          ref="editCateFormRef"
          label-width="100px"
        >
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="removeCate">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 6, 9, 12]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script lang="js">
import { columns } from "./config.js";
export default {
  name: 'Cate',
  data() {
    return {
      //商品列表数据分类，默认为空
      cateList: [],
      //查询参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //总条数
      total: 0,
      //table的表单数据
      columns:columns,
      //添加分类的弹框
      AddCateDialogVisible:false,
      //添加分类的项
      addCateForm:{
        cat_name:'',
        cat_pid:0,
        cat_level:0
      },
      //添加分类规则
      addCateFormRules:{
         cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
      //父级分类的列表
      parentCateList:[],
      //指定级联选择器的配置对象
      cascaderProps:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
        checkStrictly:true,
        expandTrigger:'hover'
      },
      selectedKeys:[],
      editCateDialogVisible:false,
      cateInfo:'',
      editCateForm:{
        cat_name:''
      },
       //添加分类规则
      editCateFormRules:{
         cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },

    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类数据
    async getCateList() {
      const { data: res } =await this.$http.get('categories', {
        params: this.queryInfo,
      })
      console.log(res)
      if (res.meta.status !== 200) {
       return  this.$message.error('获取商品分类失败')
      }
      this.cateList = res.data.result
      this.total = res.data.total
      console.log(this.cateList)
    },
    //修改一页显示的条数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    //修改页数，跳转到那一页
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    showAddCateDialog(){
     //获取父级分类的数据列表
     this.getParentCateList()
      this.AddCateDialogVisible=true
    },
    //获取父级分类的数据列表
    async getParentCateList(){
      const {data:res}=await this.$http.get('categories',{
        params:{type:2}
      })
      if (res.meta.status !== 200) {
       return  this.$message.error('获取商品分类失败')
      }
      this.parentCateList=res.data
    },
    parentCateChange(){
      if(this.selectedKeys.length>0){
        //父级分类的id
        this.addCateForm.cat_pid=this.selectedKeys[this.selectedKeys.length-1]
        //为当前父级分类的等级赋值
        this.addCateForm.cat_level=this.selectedKeys.length
        return
      }else{
        //父级分类的id
        this.addCateForm.cat_pid=0
        //为当前父级分类的等级赋值
         this.addCateForm.cat_level=0
      }
    },
    addCateDialogClosed(){
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys=[]
      //父级分类的id
        this.addCateForm.cat_pid=0
        //为当前父级分类的等级赋值
         this.addCateForm.cat_level=0
    },
    addCate(){
        this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.addCateForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败!')
        }
        this.$message.success('添加分类成功!')
        this.getCateList()
        this.AddCateDialogVisible=false
      })
    },
    editCateName(cateInfo){
      this.cateInfo=cateInfo
      this.editCateForm.cat_name=cateInfo.cat_name
      this.editCateDialogVisible=true
    },
    //修改按钮
    editCate(){
       this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateInfo.cat_id}`,{
          cat_name:this.editCateForm.cat_name
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改分类失败!')
        }
        this.$message.success('修改分类成功!')
        this.getCateList()
        this.editCateDialogVisible=false
      })
    },
    editCateDialogClosed(){
       this.$refs.editCateFormRef.resetFields()
    },
       //取消按钮
    removeCate(){
      this.editCateDialogVisible=false
      this.$message.info('已取消修改')
    },
     //删除按钮
    async removeUserById(id) {
      //使用element-ui的控件方法
      const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //如果用户确认删除，则返回字符串confirm
      //如果用户取消了删除，则返回的字符串为cancel
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getCateList()
    },
  },
}
</script>

<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
</style>
